<?php

namespace plugin\ycMassage\app\api\controller;

use app\common\service\UploadService;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageMch;
use plugin\ycMassage\app\model\MassageMchQualifications;
use plugin\ycMassage\app\model\MassageMchThumb;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\validate\MassageMch as ValidateMassageMch;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\MchQualifications;
use plugin\ycMassage\utils\enum\NoticeType;
use plugin\ycMassage\utils\notice\Notice;
use support\Request;
use think\facade\Db;

class MchController extends BaseController
{
    protected $noNeedLogin = ["details"];
    public function details(Request $request)
    {
        $id = $request->get('mch_id');
        if (!$id) {
            return $this->fail('未找到商户信息');
        }
        $saas_appid = $request->appid;
        if ($request->saas_appid) {
            $saas_appid = $request->saas_appid;
        }
        $where = [];
        $where['s.id'] = $id;
        $where['s.saas_appid'] = $saas_appid;
        $model = MassageMch::alias('s')->where($where);
        $model->join('massage_user u', 'u.id = s.uid', 'LEFT');
        $field = [
            's.id,s.title, s.logo, s.province, s.city, s.area, s.street,s.address',
            'u.nickname,u.headimg'
        ];
        $model->field($field);
        $Find = $model->find();
        if (!$Find) {
            return $this->fail('未找到商户信息');
        }
        if ($Find->nickname) {
            $Find->nickname = base64_decode($Find->nickname);
        }
        if (strpos($Find->headimg, 'http') !== 0) {
            $Find->headimg = UploadService::url($Find->headimg);
        }
        return $this->successRes($Find);
    }
    public function info(Request $request)
    {
        $model = MassageMch::where(['uid' => $request->uid, 'saas_appid' => $request->saas_appid])->find();
        if ($model) {
            $model->thumb = MassageMchThumb::where(['mch_id' => $model->id, 'saas_appid' => $request->saas_appid])->field('id,url')->select()->toArray();
            $model->qualifications = MassageMchQualifications::where(['mch_id' => $model->id, 'saas_appid' => $request->saas_appid])->field('id,url')->select()->toArray();
            return $this->successRes($model);
        }
        return $this->fail('未找到商户信息');
    }
    public function apply(Request $request)
    {
        $D = $request->post();
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $config = getHpConfig('', $request->appid, 'mch');
        $MassageUser = MassageUser::where(['id' => $uid, 'saas_appid' => $saas_appid])->find();
        if (isset($config['force_realname']) && $config['force_realname'] && $MassageUser && !$MassageUser->realname) {
            return $this->fail('请先实名认证');
        }
        $validate = new ValidateMassageMch;
        if (!empty($config['qualifications'])) {
            $qualifications = [];
            foreach ($config['qualifications'] as $key => $value) {
                $qualifications[] = MchQualifications::getText($value)['text'];
            }
            $validate->append('qualifications', 'require|array|length:' . count($qualifications));
            $validate->message([
                'qualifications.require' => '请确认是否上传：' . implode('、', $qualifications),
                'qualifications.array' => '请确认是否上传：' . implode('、', $qualifications),
                'qualifications.length' => '请确认是否上传：' . implode('、', $qualifications),
            ]);
        }
        if (!$validate->scene('apply')->check($D)) {
            return $this->fail($validate->getError());
        }
        Db::startTrans();
        try {
            $model = MassageMch::where(['uid' => $uid, 'saas_appid' => $saas_appid])->find();
            if (!$model) {
                $model = new MassageMch;
                $model->uid = $uid;
                $model->saas_appid = $saas_appid;
            }
            $model->title = $D['title'];
            $model->logo = $D['logo'];
            $model->address = $D['address'];
            $model->name = $D['name'];
            $model->mobile = $D['mobile'];
            $model->tel = $D['tel'];
            $model->province_id = (int)$D['province_id'];
            $model->province = $D['province'];
            $model->city_id = (int)$D['city_id'];
            $model->city = $D['city'];
            $model->area_id = (int)$D['area_id'];
            $model->area = $D['area'];
            if (!empty($D['street_id'])) {
                $model->street_id = (int)$D['street_id'];
                $model->street = $D['street'];
            } else {
                $model->street_id = null;
                $model->street = '';
            }
            $model->examine = Examine::WAIT['value'];
            $model->save();
            # 技师照片
            $MassageMchThumb = new MassageMchThumb;
            $thumb = [];
            foreach ($D['thumb'] as $key => $value) {
                $temp = [
                    'mch_id' => $model->id,
                    'saas_appid' => $saas_appid,
                    'url' => $value['url'],
                ];
                if (isset($value['id'])) {
                    $temp['id'] = $value['id'];
                }
                krsort($temp);
                $thumb[] = $temp;
            }
            $MassageMchThumb->saveAll($thumb);
            # 从业资格证
            $MassageMchQualifications = new MassageMchQualifications;
            $qualifications = [];
            foreach ($D['qualifications'] as $key => $value) {
                $temp = [
                    'mch_id' => $model->id,
                    'saas_appid' => $saas_appid,
                    'url' => $value['url'],
                ];
                if (isset($value['id'])) {
                    $temp['id'] = $value['id'];
                }
                krsort($temp);
                $qualifications[] = $temp;
            }
            if (!empty($qualifications)) {
                $MassageMchQualifications->saveAll($qualifications);
            }
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
        $notice = new Notice();
        $notice->saas_appid = $model->saas_appid;
        $notice->role = ['ADMIN'];
        $notice->type = NoticeType::WORK_ORDER['value'];
        $notice->setData([
            'service_name' => '商户入驻审核',
            'name' => $model->title . '(' . $model->id . ')',
            'time' => date('Y-m-d H:i:s'),
        ]);
        $notice->send();
        return $this->success('申请成功,请等待审核');
    }
    public function deleteImage(Request $request)
    {
        $id = $request->post('id');
        $name = $request->post('name');
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $mch_id = MassageMch::where(['uid' => $uid, 'saas_appid' => $saas_appid])->column('id');
        switch ($name) {
            case 'thumb':
                $model = MassageMchThumb::where(['id' => $id, 'saas_appid' => $saas_appid])->whereIn('mch_id', $mch_id)->find();
                break;
            case 'qualifications':
                $model = MassageMchQualifications::where(['id' => $id, 'saas_appid' => $saas_appid])->whereIn('mch_id', $mch_id)->find();
                break;
            default:
                return $this->fail('未找到图片');
                break;
        }
        if ($model) {
            $model->delete();
            return $this->success('删除成功');
        }
        return $this->fail('未找到图片');
    }
}
